package pers.vic.upload.socket.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import pers.vic.upload.config.UploadProperties;
import pers.vic.upload.constant.SessionAttr;
import pers.vic.upload.login.service.LoginService;
import pers.vic.upload.socket.handler.SocketUploadHandler;
import pers.vic.upload.socket.service.UploadHandlerService;

import java.util.HashSet;
import java.util.Set;

/**
 * 描述: webSocket 配置
 * @author Vic.xu
 * @date 2022-06-07 9:50
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private UploadHandlerService uploadHandlerService;

    /**
     * 文件分片大小
     */
    private int curPartSize = 512 * 1024;

    @Autowired
    private UploadProperties uploadProperties;

    @Autowired
    private LoginService loginService;


    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(curPartSize);
        container.setMaxBinaryMessageBufferSize(curPartSize + 1024);
        return container;
    }

    /*
        Set<String> sessionAttributes = new HashSet<>();
        sessionAttributes.add(SessionAttr.USER_ID);
        sessionAttributes.add(SessionAttr.USER_NAME);
        sessionAttributes.add(SessionAttr.SESSION_USER);
        HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor(sessionAttributes);
        interceptor.setCopyHttpSessionId(true);
     */

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

        MineHttpSessionHandshakeInterceptor mimeInterceptor = new MineHttpSessionHandshakeInterceptor();
        mimeInterceptor.setNeedLogin(uploadProperties.isNeedLogin());
        mimeInterceptor.setLoginService(loginService);
        SocketUploadHandler uploadHandler = new SocketUploadHandler(uploadHandlerService);
        registry.addHandler(uploadHandler, "/ws/upload").addInterceptors(mimeInterceptor).setAllowedOrigins("*");
    }
}
